﻿
using CSharpLibs.Annotations;

namespace System.IO
{
	[Builtin]
	public class StreamWriter : TextWriter
	{
		private Stream stream;

		public StreamWriter(Stream strm)
		{ this.stream = strm; }

		public StreamWriter(string path)
		{ this.stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read); }

		public override void Close()
		{
			if(this.stream != null)
			{
				Stream s = this.stream;
				this.stream = null;
				s.Close();
			}
		}

		public override void Write(char value)
		{ this.stream.WriteByte((byte)value); }

		public override void Write(char[] buffer)
		{
			byte[] bytes = new byte[buffer.Length];
			for(int i = 0; i < buffer.Length; ++i)
				bytes[i] = (byte)buffer[i];

			this.stream.Write(bytes, 0, bytes.Length);
		}

		public override void Write(string value)
		{
			this.Write(value.ToCharArray());
		}

		public override void Write(char[] buffer, int index, int count)
		{
			byte[] bytes = new byte[count];
			for(int i = 0; i < count; ++i)
				bytes[i] = (byte)buffer[index + i];

			this.stream.Write(bytes, 0, bytes.Length);
		}
	}
}
